package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWork {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 开始时间戳，用于计算序列号
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L; // 2022-01-01 00:00:00
    private static final int COUNT_BITS = 32; // 序列号位数
    // id生成的策略
    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 2.生成序列号(有上限) ：不能永远使用同一个key
        // 2.1.获取当前日期，精确到天(方便统计)
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 2.2.自增长 （不会出现空指针）
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // 3.拼接并且返回（位运算）

        return timestamp << COUNT_BITS | count;
    }
    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }
}
